package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;

/**
 * @Author XHui
 * @Since 2024/2/4 12:38
 * @Version 1.0
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    /**
     * 登录
     *
     * @param dto DTO
     * @return 通用的结果返回类
     */
    @Transactional
    @Override
    public ResponseResult login(AdUserDTO dto) {
        // 1. 校验参数 保证name password不为空
        if (dto == null)
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "用户名和密码不能为空");
        if( StringUtils.isBlank( dto.getName() ) )
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "用户名不能为空");
        if(StringUtils.isBlank(dto.getPassword()))
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "密码不能为空");
        
        // 2. 根据name查询用户信息
        AdUser queriedAdUserByName = this.getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        if(queriedAdUserByName == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在或密码错误");
        }
        // 3. 判断用户输入的密码 和 数据库查询的盐值进行加密处理后，和数据库的密文进行比对
        String salt = queriedAdUserByName.getSalt();
        String password = queriedAdUserByName.getPassword();
        String encryptedPassword = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
        //String encryptedPassword = MD5Utils.encodeWithSalt(dto.getPassword(), salt);
        if(!ObjectUtils.equals(password, encryptedPassword)){ // 密码匹配失败
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "用户名不存在或密码错误");
        }
        // 4. 判断用户状态是否正常， 正确（9）
        if(queriedAdUserByName.getStatus() != 9){
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR, "用户状态异常,请联系管理员");
        }
        // 5. 修改最近登录时间
        queriedAdUserByName.setLoginTime(new Date());
        this.updateById(queriedAdUserByName);
        // 6. 颁发token， 返回token和 user
        String token = AppJwtUtil.getToken(queriedAdUserByName.getId().longValue());
        HashMap<String, Object> resultMap = new HashMap<>();
        AdUserVO adUserVO = new AdUserVO();
        BeanUtils.copyProperties(queriedAdUserByName, adUserVO);
        resultMap.put("token", token);
        resultMap.put("user", adUserVO);
        return ResponseResult.okResult(resultMap);
    }

    public static void main(String[] args) {
        Integer a = 9;
        System.out.println(a == 9);
    }
}
